//
//  NewsViewController.m
//  XIWenLeJian
//
//  Created by lanou3g on 15/11/11.
//  Copyright © 2015年 蓝足. All rights reserved.
//

#import "NewsViewController.h"
#import "NewsModel.h"
#import "NewsNetWorkTool.h"
#import "UserInfo.h"
#import "MJRefresh.h"
#import "FileHandle.h"
#import "NewsTableViewCell.h"
#import "TopImageTableViewCell.h"
#import "ThreeImagesTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "LongTableViewCell.h"
#import "LoginViewController.h"
#import "CollectTableViewController.h"
#import "NewsDetailViewController.h"
// 网络判断
#import "AFNetworking.h"
#import "MJExtension.h"

#define KScreenHeight [UIScreen mainScreen].bounds.size.height

@interface NewsViewController ()

@property (nonatomic,strong) NSMutableData *newsData;
@property (nonatomic,strong) NSMutableArray *listArray;
@property (nonatomic,strong) NSMutableArray *anotherListArray;
@property (nonatomic,strong) NSString *state;
@property (nonatomic,strong) UIImageView *rightHeadImageView;
@end

@implementation NewsViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (![UserInfo shareUserInfo].isJudge) {
        [self changeInternet];
        [UserInfo shareUserInfo].isJudge = YES;
    }
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.title = @"News";
    [self refresh];
}

// cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsModel *model = self.listArray[indexPath.row];
    if (model.hasHead) {
        return [TopImageTableViewCell addTopImageCellWithTableView:tableView model:model];
    }else if (model.imgType) {
        return [LongTableViewCell addLongImageCellWithTableView:tableView model:model];
    }else if (model.imgextra){
        return [ThreeImagesTableViewCell addThreeImagesCellWithTableView:tableView model:model];
    }else{
        return [NewsTableViewCell addNewsCellWithTableView:tableView model:model];
    }
}

// 单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self heightForRow:self.listArray[indexPath.row]];
}

- (CGFloat)heightForRow:(NewsModel *)model
{
    if (model.hasHead) {
        return KScreenHeight * 0.36;
    }else if (model.imgType){
        return KScreenHeight * 0.25;
    }else if (model.imgextra){
        if (KScreenHeight * 0.2 < 130) {
            return 130;
        }else{
            return KScreenHeight * 0.2;
        }
    }else{
        if (KScreenHeight * 0.15 < 100) {
            return 100;
        }else{
            return KScreenHeight * 0.15;
        }
    }
}


// cell 的点击处理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   // 刚选中马上取消选中， 不变色
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NewsDetailViewController *newsDetailVC = [[NewsDetailViewController alloc]init];
    NewsModel *model = self.listArray[indexPath.row];
    // 顶部图片网址
    if (model.skipID != nil) {
        NSString *newStr = [model.skipID stringByReplacingOccurrencesOfString:@"|" withString:@"/"];
        NSString *newUrl = [NSString stringWithFormat:@"http://ent.163.com/photoview/%@.html", newStr];
        model.url_3w = newUrl;
    }
      // 本地 plist 存在即为收藏
    if ([UserInfo shareUserInfo].isLogin) {
        if ([[FileHandle fileHandle]foundNewsForID:model.docid]) {
            model.isCollect = YES;
        }
    }
    // 传值给下个页面
    newsDetailVC.newsModel = model;
    [self.navigationController pushViewController:newsDetailVC animated:YES];
}

#pragma mark>>>>>>>>>>>>>>>>>>>> 数据
- (void)refresh
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    header.automaticallyChangeAlpha = YES;
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    // 马上进入刷新状态
    [header beginRefreshing];
    
    // 设置header
    self.tableView.header = header;
    
    
     MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    // 设置文字
    [footer setTitle:@"点击和上拉会加载更多" forState:(MJRefreshStateIdle)];
    [footer setTitle:@"正在加载更多" forState:(MJRefreshStatePulling)];
    [footer setTitle:@"没有更多了" forState:(MJRefreshStateNoMoreData)];
    
    // 字体
    footer.stateLabel.font = [UIFont systemFontOfSize:15];
    footer.stateLabel.textColor = [UIColor grayColor];
    self.tableView.footer = footer;

}

// 上拉刷新
- (void)loadNewData
{
    NSString *string = @"http://c.m.163.com/nc/article/list/T1348648517839/0-20.html";
    [self loadDataForType:1 withURL:string];
}

// 上拉加载
- (void)loadMoreData
{
    NSString *allUrlstring = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/list/T1348648517839/%ld-20.html",(self.listArray.count - self.listArray.count%10)];
    [self loadDataForType:2 withURL:allUrlstring];

    
}

// 解析方法
- (void)loadDataForType:(int)type withURL:(NSString *)allUrlstring
{
    [[[NewsNetWorkTool sharedNetworkTools] GET:allUrlstring parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary* responseObject) {
        NSString *key = [responseObject.keyEnumerator nextObject];
        
        NSArray *temArray = responseObject[key];
        
        NSMutableArray *arrayM = [NewsModel objectArrayWithKeyValuesArray:temArray];
        if (type == 1) {
            self.listArray = arrayM;
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
        }else if(type == 2){
            [self.listArray addObjectsFromArray:arrayM];
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }] resume];
}



#pragma mark>>>>>>>>>>>>>>>>>>检测网络变化
- (void)changeInternet
{
    // 建立网络状态监控类， 单例
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 当网络发生变化时调用这个block
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WIFI");
                self.state = @"您当前为WIFI连接";
                [self judgeInternet];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"自带网络");
                self.state = @"您当前网络为数据流量";
                [self judgeInternet];
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                self.state = @"您当前无网络连接,请设置";
               [self judgeInternet];
                break;
                
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络");
                self.state = @"您当前为未知网络，请检查网络是或否安全";
               [self judgeInternet];
                break;
            default:
                break;
        }
    }];
        [mgr startMonitoring];
}

// 如果控制器没了， 就不要监听了
- (void)dealloc
{
    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
}

- (void)judgeInternet
{
    // 初始化alertView
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:self.state delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
    [alert show];
}

@end
